package com.js.nickcar.base;

import com.js.nickcar.entity.remote.ApiResultBean;
import com.js.nickcar.widget.recycler.BaseRecyclerAdapter;
import com.zyzd.commontools.log.TLog;

import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;


/**
 * Created by LZY on 2017/9/29.
 */

public abstract class BaseRecyclerPresenter<T, V extends BaseRecyclerView> extends BasePresenter<V> {
    protected static int initPageIndex = 0;
    protected boolean mIsRefresh;
    protected boolean hasMore;
    public int nextPageIndex;
    protected ArrayList<T> mList = new ArrayList<>();


    public void onRefreshing() {
        mIsRefresh = true;//true 表示主动刷新
        nextPageIndex = initPageIndex;
        hasMore = true;
        requestData();
    }

    public void requestData() {
        Observable<ApiResultBean<ArrayList<T>>> observable = getObservable();
        addSubscription(observable.map(new HttpResultFunc<ArrayList<T>>()), getResultSubscriber());
    }

    public abstract Observable<ApiResultBean<ArrayList<T>>> getObservable();

    protected Subscriber<ArrayList<T>> getResultSubscriber() {
        return new ApiCallback<ArrayList<T>>() {
            @Override
            public void onSuccess(ArrayList<T> data) {
                TLog.d("zyzd", "BaseRecyclerPresenter>>onSuccess--> " + data);
                parseData(data);
            }

            @Override
            public void onFailure(String msg) {
                mView.onComplete();
                TLog.d("zyzd", "BaseRecyclerPresenter>>onSuccess--> " + msg);
            }

            @Override
            public void onFinish() {
                mView.onComplete();
                TLog.d("zyzd", "BaseRecyclerPresenter>>onFinish--> ");
            }
        };
    }

    protected void parseData(ArrayList data) {
        mList = data;
        nextPageIndex++;//请求成功后，修改下一页

        if (mIsRefresh) {//主动刷新
            mView.refreshSuccess(mList);
        } else {
            mView.loadMoreSuccess(data);
        }

        if (data.size() < getPageSize()) {
            hasMore = false;
            mView.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
        }
    }

    protected int getPageSize() {
        return 10;
    }

    public void onLoadMore() {
        if (hasMore) {
            mView.setState(BaseRecyclerAdapter.STATE_LOAD_MORE, true);
            requestData();
        } else {//避免出现当没有更多数据时，导致下拉刷新失效
            mView.onComplete();
        }
    }

    public void setRefreshState(boolean refreshState) {
        mIsRefresh = refreshState;
    }
}
